package com.clqteam.daoimpl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.clqteam.dao.InsertTempOrderDao;
import com.clqteam.model.Product;
import com.clqteam.util.JDBCutil;

public class InsertTempOrderDaoImpl implements InsertTempOrderDao{

	@Override
	public int insetTempOrderInfo(int ptId, int ptAmount,String tbName) {
		int flag = -1;
		StringBuffer sql = new StringBuffer();
		sql.append("INSERT INTO ");
		sql.append(tbName);
		sql.append(" (ptId,ptAmount) VALUES(?,?)");
		Connection con = JDBCutil.getConnection();
		try {
			PreparedStatement pst = con.prepareStatement(sql.toString());
			pst.setInt(1, ptId);
			pst.setInt(2, ptAmount);
			flag = pst.executeUpdate();
			JDBCutil.closeJDBC(pst, con);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}	
		return flag;
	}

	@Override
	public List<Product> getExist(String tbName) {
		List<Product> pros = new ArrayList<>();
		StringBuffer sql = new StringBuffer();
		sql.append("SELECT ptId,ptamount FROM ");
		sql.append(tbName);
		Connection con = JDBCutil.getConnection();
		try {
			PreparedStatement pst = con.prepareStatement(sql.toString());
			ResultSet rs = pst.executeQuery();
			while(rs.next()){
				Product pro = new Product();
				pro.setPoAmount(rs.getInt("ptamount"));
				pro.setpId(rs.getInt("ptId"));
				pros.add(pro);				
			}
			JDBCutil.closeJDBC(pst, con);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}		
		return pros;
	}

	@Override
	public int updateTempOrderInfo(int ptId, int ptAmount,String tbName) {
		int flag = -1;
		StringBuffer sql = new StringBuffer();
		sql.append(" UPDATE ");
		sql.append(tbName);
		sql.append(" SET ptamount = ? WHERE ptId = ?");
		Connection con = JDBCutil.getConnection();
		try {
			PreparedStatement pst = con.prepareStatement(sql.toString());
			pst.setInt(2, ptId);
			pst.setInt(1, ptAmount);
			flag = pst.executeUpdate();
			JDBCutil.closeJDBC(pst, con);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}				
		return flag;
	}
}
